package com.mall.controller;



import com.mall.common.exception.BadRequestException;
import com.mall.common.utils.BeanUtils;
import com.mall.common.utils.CollUtils;
import com.mall.common.utils.UserContext;
import com.mall.domain.dto.AddressDTO;
import com.mall.domain.dto.AddressDTO2;
import com.mall.domain.po.Address;
import com.mall.domain.response.Response;
import com.mall.service.IAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/addresses")
@RequiredArgsConstructor
@Api(tags = "收货地址管理接口")
public class AddressController {

    private final IAddressService addressService;

    @ApiOperation("根据id查询地址")
    @GetMapping("{addressId}")
    public AddressDTO findAddressById(@ApiParam("地址id") @PathVariable("addressId") Long id) {
        // 1.根据id查询
        Address address = addressService.getById(id);
        // 2.判断当前用户
        Long userId = UserContext.getUser();
        if(!address.getUserId().equals(userId)){
            throw new BadRequestException("地址不属于当前登录用户");
        }
        return BeanUtils.copyBean(address, AddressDTO.class);
    }
    @ApiOperation("查询当前用户地址列表")
    @GetMapping
    public List<AddressDTO> findMyAddresses() {
        // 1.查询列表
        List<Address> list = addressService.query().eq("user_id", UserContext.getUser()).list();
        // 2.判空
        if (CollUtils.isEmpty(list)) {
            return CollUtils.emptyList();
        }
        // 3.转vo
        return BeanUtils.copyList(list, AddressDTO.class);
    }

    /**
     * 查看收货地址
     */
    @GetMapping("/address")
    public Response<List<AddressDTO2>> getAddress(){
        return addressService.getAddress();
    }
    /**
     * 新增收货地址
     */
    @PutMapping("/address")
    public Response<?> addAddress(String province,String city,String town,String street,String username,String mobile){
        return addressService.addAddress(province,city,town,street,username,mobile);
    }
    /**
     * 删除收货地址
     */
    @DeleteMapping("/address")
    public Response<?> deleteAddress(@RequestParam ArrayList<Long> ids){
        return addressService.deleteAddress(ids);
    }
    /**
     * 编辑收货地址
     */
    @PutMapping("/edit")
    public Response<?> editAddress(@RequestBody Address address){
        return addressService.editAddress(address);
    }
    /**
     * 设为默认
     */
    @PutMapping("/is_default")
    public Response<?> is_default(Long id){
        return addressService.is_default(id);
    }
    /**
     * 查询默认收货地址
     */
    @GetMapping("/defaultAddress")
    public Response<Address> defaultAddress(){
        return addressService.defaultAddress();
    }
}
